# $Id: FilterStatsSimple.pm,v 1.1 2004/02/29 19:18:42 ibo Exp $

package CGI::FOGE2::FilterStatsSimple;
use strict;
use CGI::FOGE2::Tools;
our @ISA = qw(CGI::FOGE2::FilterStats);

=head1 SYNOPSIS

StatsSimple - report histogram frequencies for a closed question.

=head1 DESCRIPTION

This is currently the default statistics maker. It extracts data from
the DB and computes an histogram (taking care of multiple answers).

Actually, new([0 .. 3]) produces 4 different types of statistics.  By
default, new() is equivalent to new([0, 2]) producing count and
frequencies (in percent).

=cut

sub new {
    my $proto = shift;
    my $params = [ @_ ];
    my $class = ref($proto) || $proto;

    my @mandatory_keys = ();
    my $self  =
	{
        #TODO: this code should be inherited rather than copied        FUTURE
        answer   => theform->{dbAnswer},
        enquiry  => theform->{enquiry},
        relation => undef,
        columns  => undef,
        question => undef,
        types    => [],
        params   => $params,
        caption  => undef,
	};

    bless ($self, $class);
    return $self;
}

sub getstats {
    my $self = shift;
    my $out = '';

    my ($number, $total, $names, $vals) = $self->computedata();
    # Sort answer with the order set by the original question
    ($number, $total, $names, $vals) = 
        $self->{question}->sort($number, $total, $names, $vals);

    my ($vtot, $vpcent, $vpcenttot) = ([], [], []);
    my $subtotal = 0;
    foreach my $val (@$vals) {
        $subtotal += $val;
        #push @$vtot,      sprintf "%d/%d", $subtotal, $total;
        push @$vtot,      sprintf "%d", $subtotal;
        push @$vpcent,    sprintf "%.0f%%", ($val/$total) * 100;
        push @$vpcenttot, sprintf "%.0f%%", ($subtotal/$total) * 100;
    }

    my $table = '';
    foreach my $tab ($names) {
        my $line = '';
        foreach ('', @$tab) {
            $line .= CGI::th({-class => 'statrow'}, $_);
        }
        $table .= CGI::Tr({-class => 'statrow'}, $line);
    }

    my $computations = $self->{params}[0] || [0, 2];

    my @statsums = ($vals, $vtot, $vpcent, $vpcenttot);
    foreach my $i (@$computations) {
        my $line = '';
        my $tab = $statsums[$i];
        $line .= CGI::td({-class => 'stat1stcol'},
                         msg->stats_row_names->[$i++]);	
        foreach (@$tab) {
            $line .= CGI::td({-class => 'statrow'}, $_);
        }
        $table .= CGI::Tr({-class => 'statrow'}, $line);
    }
    if ( defined $self->{caption} ) {
        $out = CGI::table(CGI::caption($self->{caption}), $table);
    } else {
        $out = CGI::table($table);
    }
    return $out;
}

1;
